package com.example.erat.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<Map<String, Object>> handleBusinessException(BusinessException e) {
        log.error("业务异常: {}", e.getMessage(), e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", e.getCode());
        result.put("message", e.getMessage());
        
        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }
    
    /**
     * 处理文件解析异常
     */
    @ExceptionHandler(FileParseException.class)
    public ResponseEntity<Map<String, Object>> handleFileParseException(FileParseException e) {
        log.error("文件解析异常: {}", e.getMessage(), e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", e.getCode());
        result.put("message", e.getMessage());
        
        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }
    
    /**
     * 处理学生文件名异常
     */
    @ExceptionHandler(StudentFileNameException.class)
    public ResponseEntity<Map<String, Object>> handleStudentFileNameException(StudentFileNameException e) {
        log.error("学生文件名异常: {}", e.getMessage(), e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", e.getCode());
        result.put("message", e.getMessage());
        
        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }
    
    /**
     * 处理未知异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleException(Exception e) {
        log.error("系统异常: {}", e.getMessage(), e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", "500");
        result.put("message", "系统内部错误: " + e.getMessage());
        
        return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
    }
} 